<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class ActivityOrders extends BaseModel
{
    protected $table = 'activity_orders';

    protected $hidden = ['openid','send_pass'];

    public function user()
    {
        return $this->belongsTo('App\User','user_id','id');
    }

    public function activity()
    {
        return $this->belongsTo('App\Model\Activity','activity_id','id');

    }

    public function helps()
    {
        return $this->hasMany('App\Model\ActivityHelp','activity_order_id','id');
    }

    public function getApplyStatusAttribute()
    {
        $arr = [0=>'申请未通过',1=>'助力中',2=>'助力完成',3=>'申请通过',4=>'待收货',5=>'已完成',6=>'活动已结束',7=>'已反馈'];
        return isset($arr[$this->state])?$arr[$this->state]:$this->state;
    }

    public function getDeadLineAttribute()
    {
        $ts = strtotime($this->activity->end_time) - time();
        $d = ceil($ts/86400);
        return  $d>0?$d:0;
    }

    public function changeApplyStateByHelp()
    {
        $this->old = $this->helps()->where('isNewUser','=',0)->count();
        $this->new = $this->helps()->where('isNewUser','=',1)->count();
        $this->apply_rule = $this->activity->share_rule;

        if ($this->old+$this->new >= $this->apply_rule){
            $this->apply_state = 1;
            $this->apply_pass_time = date('Y-m-d H:i:s');
            if($this->state == 1) $this->state = 2;
        }

        return $this->save();
    }

    public static function changeState($activity,$finished=true)
    {
        if ($activity->sign_count>=$activity->participate_limit) {
            DB::table('activity_orders')->where('state','=',2)->where('activity_id','=',$activity->id)
                ->update(['state' => 0]);
        }

        //更改其它报名
        if ($activity->state=="finished") {
            return DB::table('activity_orders')->where('state','=',1)->where('activity_id','=',$activity->id)
                ->update(['state' => 6]);
        }elseif(!$finished){
            return DB::table('activity_orders')->where('state','=',6)->where('activity_id','=',$activity->id)
                ->update(['state' => 1]);
        }
        return false;
    }

}
